/**
 * 高数卡口预警分析
 */
$(function(){
	NightDrivingAna.init();
});

var NightDrivingAna = {
	param: {},
init: function(){
	var me = this;
	me.myChart=null;
	me.initQueryTime();
	me.intEnterprise();
	me.initTollStation();
	me.barChart = me.initEnterpiseBarChart();
	me.pieChart = me.initTollStationBarChart();
	me.loadTableTitle();
	me.initEvent();
},
initEvent: function(){
	var me = this;
	var startTime=$("#inputStartDate").val();
   	var endTime=$("#inputEndDate").val();
   	var vehicleId=$("#selectEnterprise").val();
   	var unitId=$("#selectTollStation").val();
   
	$("#queryBtn").click(function(){
		
	});
	$("#exportExcel").click(function(){
		me.exportExcel();
	});
},
initQueryTime:function(){
	var todayDate = new Date();
	var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
	var beforeDate = new Date(todayDate-86400000*1); //前一天
	var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	if (mm.length == 1) {
	    mm = '0' + mm;
	}
	if (dd.length == 1) {
	    dd = '0' + dd;
	}
	$("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
	$("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
 },
intEnterprise: function(){
	$('#selectEnterprise').select2({
		theme: "default",
	        allowClear: true,
	        placeholder: "全部业户",
	        ajax:{
	            url:appCtx + "base/report/RegionalStatistics/getQueryEnterAndPlatByRole.html",
	            dataType:"json",
	            delay:250,
	           async : true,
	            data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部业户"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.areaId, "text":obj.entName};
 	                    options.push(option);
	    				});
 	                return {
 	                	results: options,
 	                    pagination: {
 	                        more:false
 	                    }
 	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	})
	/*var me = this;
	$.ajax({
		type : 'post',
		url : appCtx + "base/report/RegionalStatistics/getQueryEnterAndPlatByRole.html",
		cache : false,
		dataType : "JSON",
		success : function(data) {
				var selectStry="<option value=''>业户查询</option>";
				$.each(data,function(index,f){
					selectStry+="<option value='"+f.id+"'>"+f.entName+"</option>";
				});
				$('#selectEnterprise').html(selectStry);		
				$("#selectEnterprise").select2();
			}
	});*/

},
initTollStation:function(){
	var me = this;
	 var selectStr="<option value=''>请选择收费站</option>";
		$('#selectTollStation').html(selectStr);		
		$("#selectTollStation").select2();
		$("#selectTollStation").change(function(){
			var unitId = $(this).children('option:selected').val(); 
		})
/*    	$.ajax({
    		type : 'post',
    		async : false,
    		url : appCtx + "/report/convoyRunning/loadVehicleUnit.html",
    		cache : false,
    		dataType : "JSON",
    		success : function(data) {			
    			if(data){
    				 var selectStr="<option value=''>请选择</option>";
    				for(var i=0;i<data.length;i++){
    					selectStr+="<option value='"+data[i].id+"'>"+data[i].name+"</option>";
    				}
    				$('#selectTollStation').html(selectStr);		
    				$("#selectTollStation").select2();
    			}
    		}
    	});*/
		$("#selectTollStation").next().css("border","none");
},
initEnterpiseBarChart: function(){
	var me = this;
	//计算显示的柱子数
	var percent = 100;

	option = {
	    color: ['#3398DB'],
	    legend: {
            data:['企业统计次数']
        },
	    tooltip : {
	        trigger: 'axis',
	        show: true,
	        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
	        	show: false,
	            type : 'none'        // 默认为直线，可选为：'line' | 'shadow'
	        },
	        formatter:function(a){
	        	if(a[0].name==''){
	        		return;
	        	}
	        	var relVal = "";
	        	relVal = a[0].name+"："+a[0].value+"次";
	        	return relVal;
	        }
	    },
	    grid: {
	        left: '3px',
	        top:'10%',
	        right: '10px',
	        containLabel: true
	    },
	    xAxis : [
	        {
	            type : 'category',
	            data : [],
	            axisTick: {
	                alignWithLabel: true
	            },
	            axisLabel:{
	            	textStyle: {
                        fontSize: 10
                    }
	            }
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value',
	            show: true,    //显示纵轴false-不显示，true-显示
	            min: 0,
		    	minInterval: 1,
		    	axisLabel: {
                      formatter: function (value, index) {
                    	  if (value >= 1 || value == 0) {
                          	if (value%1 === 0) {
                          		return value;
                          	}
                          }
                        }
                 },
	            name: '次数'
	        }
	    ],
	    series : [
	        {
	            name:'企业统计次数',
	            type:'bar',
	            barWidth: '60%',
	            data:[]
	        }
	    ],
	    dataZoom: [{
	        type: 'inside',
	        start: 0,
	        end: percent
	    }, {
	        start: 0,
	        end: percent,
	        fillerColor:'#A3E1A3',
	        handleColor:'#83A7D1',
	        showDetail:false	
	    }]
	};
        var myChart = echarts.init(document.getElementById('barChart'));
        myChart.setOption(option);
        window.onresize = myChart.resize;
        
        myChart.on('click', function(param){
        	var vehicleIdList = me.vehicleIdList;
        	var vehicleId = vehicleIdList[param.dataIndex];
        	me.queryNightDrivingTable(vehicleId,param.name);
        });
        
        return {
        	refash : function(option){
                myChart.setOption(option);
        	},
        	option : option,
        	barChartDom : myChart
        };        
},


initTollStationBarChart: function(){
	var me = this;
	//计算显示的柱子数
	var percent = 100;

	option = {
	    color: ['#3398DB'],
	    legend: {
            data:['收费站统计次数']
        },
	    tooltip : {
	        trigger: 'axis',
	        show: true,
	        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
	        	show: false,
	            type : 'none'        // 默认为直线，可选为：'line' | 'shadow'
	        },
	        formatter:function(a){
	        	if(a[0].name==''){
	        		return;
	        	}
	        	var relVal = "";
	        	relVal = a[0].name+"："+a[0].value+"次";
	        	return relVal;
	        }
	    },
	    grid: {
	        left: '3px',
	        top:'10%',
	        right: '10px',
	        containLabel: true
	    },
	    xAxis : [
	        {
	            type : 'category',
	            data : [],
	            axisTick: {
	                alignWithLabel: true
	            },
	            axisLabel:{
	            	textStyle: {
                        fontSize: 10
                    }
	            }
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value',
	            show: true,    //显示纵轴false-不显示，true-显示
	            min: 0,
		    	minInterval: 1,
		    	axisLabel: {
                      formatter: function (value, index) {
                    	  if (value >= 1 || value == 0) {
                          	if (value%1 === 0) {
                          		return value;
                          	}
                          }
                        }
                 },
	            name: '次数'
	        }
	    ],
	    series : [
	        {
	            name:'收费站统计次数',
	            type:'bar',
	            barWidth: '60%',
	            data:[]
	        }
	    ],
	    dataZoom: [{
	        type: 'inside',
	        start: 0,
	        end: percent
	    }, {
	        start: 0,
	        end: percent,
	        fillerColor:'#A3E1A3',
	        handleColor:'#83A7D1',
	        showDetail:false
	    }]
	};
        var myChart = echarts.init(document.getElementById('pieChart'));
        myChart.setOption(option);
        window.onresize = myChart.resize;
        
        myChart.on('click', function(param){
        	var vehicleIdList = me.vehicleIdList;
        	var vehicleId = vehicleIdList[param.dataIndex];
        	me.queryNightDrivingTable(vehicleId,param.name);
        });
        
        return {
        	refash : function(option){
                myChart.setOption(option);
        	},
        	option : option,
        	barChartDom : myChart
        };        
},
	

queryBarChart: function(){
	var me = this;
/*		$.ajax({
			type : 'post',
			async : false,
			url : appCtx+"/report/nightDriving/queryBarChartData.html?unitId="+unitId+"&vehicleId="+vehicleId+"&startTime="+startTime+"&endTime="+endTime,
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var option = me.barChart.option;
				option.xAxis[0].data = data.xAxisData;//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
				option.series[0].data = data.series;//[10, 52, 200, 334, 390, 330, 220];
				me.barChart.refash(option);
				me.vehicleIdList = data.vehicleIdList;
				
				//默认展示第一个的列表
				me.queryNightDrivingTable(data.vehicleIdList[0],data.xAxisData[0]);
			}
		})*/;
},
queryTable: function(){
	var me = this;
	/*$.ajax({
		type : 'post',
		async : false,
		url : appCtx+"/report/nightDriving/queryPieChartData.html?unitId="+unitId+"&startTime="+startTime+"&endTime="+endTime+"&vehicleId="+vehicleId,
		cache : false,
		dataType : "JSON",
		success : function(data) {
			var option = me.pieChart.option;
			if(data.legendData.length==0){
				option.legend.data = [0];
				option.series[0].data = [{'name':'无数据','value':0}];
			}else{
				option.legend.data = data.legendData;
				option.series[0].data = data.series;
			}
			
			me.pieChart.refash(option);
		}
	});*/
	
},
getColumn:function(){
	return [{
        display : '车牌号码',
        name : 'plateNumber',
        width : 8,
        sortable : false,
        align : 'left',
        showTitle : 'plateNumber'
    },{
        display : '车牌颜色',
        name : 'startDateTime',
        width : 8,
        sortable : false,
        align : 'left',
        showTitle : 'startDateTime'
    },{
        display : '收费站名称',
        name : 'endDateTime',
        width : 13,
        sortable : false,
        align : 'left',
        showTitle : 'endDateTime'
    },{
        display : '过收费站时间',
        name : 'driveTimeStr',
        width : 15,
        sortable : false,
        align : 'left',
    },{
        display : 'GPS定位位置',
        name : 'milegeStr',
        width : 13,
        sortable : false,
        align : 'left'
    },{
        display : 'GPS定位时间',
        name : 'milegeStr',
        width : 15,
        sortable : false,
        align : 'left'
    },{
        display : '所属业户',
        name : 'milegeStr',
        width : 15,
        sortable : false,
        align : 'left'
    },{
        display : '异常类型',
        name : 'milegeStr',
        width : 8,
        sortable : false,
        align : 'left'
    },{
    	display : '操作',
        name : 'Handler',
        width : 5,
        sortable : false,
        align : 'center',
        paramcolnames:['vehicle_no'],
        handlefunction:function(vehicle_no){
    		var handleStr = '<div style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img id="'+vehicle_no.substring(1,7)+'" name="trackPlayBtn" src="'+global.url.domain+'gps-web/resources/images/track.png" title="定位">定位<div>';		
    		return handleStr;
        }
    }]
},
loadTableTitle:function(){
	$("#objTable").flexigrid({
            dataType : 'json',
            colModel :this.getColumn() ,
            usepager : true,// 是否分页，默认为true。
            singleSelect:true,
			sortname : "id",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
            height:308,
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
            widthType:'%',
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
            width:$('.detail-report').width(),
         });	 
},

exportExcel : function(){
	var me = this;
	var header1 = JSON.stringify(me.getColumn());
	var header2 = JSON.parse(header1);
	
	var headerWidth = $('.detail-report').width();
	for(var i=0;i<header2.length;i++){
		header2[i].width = Math.ceil(headerWidth / 100 * header2[i].width);
	}
	header2.splice(header2.length-1,1);
	var header3 = JSON.stringify(header2);
	 var imageUrl = me.barChart.barChartDom.getDataURL({
		type: 'png',
	    pixelRatio: 1
	}); 
	 
	 var imageUrl2 = me.pieChart.pieChartDom.getDataURL({
			type: 'png',
		    pixelRatio: 1
	}); 
	 
	//表头
	var colModelList=new Array();
	colModelList.push(header3);
	var colModel= $.toJSON(colModelList);
	
	//图片
	var imgsrcList=new Array();
	imgsrcList.push(imageUrl);
	imgsrcList.push(imageUrl2);
	var imgsrc= $.toJSON(imgsrcList);
		
	var param =  {
			startTime:$("#inputStartDate").val()+" 00:00；00",
			endTime: $("#inputEndDate").val()+" 23:59:59",
			vehicleId:$("#selectEnterprise").val(),
			unitId:$("#selectTollStation").val(),
			colModel:colModel,
			title:"夜间行车分析导出",
			imgsrc:imgsrc
	};
	post(appCtx+"report/nightDriving/exportNightDriving.html",param);
	
}
};